<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <view class="back-section" @click="goBack">
          <text class="back-icon">←</text>
          <text class="header-title">对话历史</text>
        </view>
        <view class="header-actions">
          <button class="new-chat-btn" @click="createNewChat">
            <text class="new-chat-icon">💬</text>
            <text>新对话</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 对话列表 -->
    <scroll-view
      class="conversations-list"
      scroll-y="true"
      @scrolltolower="loadMore"
      refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="conversations.length === 0 && !loading" class="empty-state">
        <text class="empty-icon">💬</text>
        <text class="empty-title">暂无对话</text>
        <text class="empty-desc">开始您的第一个对话吧</text>
        <button class="empty-action-btn" @click="createNewChat">
          开始对话
        </button>
      </view>

      <view v-else class="conversations-container">
        <view
          v-for="conversation in conversations"
          :key="conversation.id"
          class="conversation-item"
          @click="openConversation(conversation)"
        >
          <view class="conversation-content">
            <view class="conversation-header">
              <text class="conversation-title">{{
                conversation.title || "新对话"
              }}</text>
              <view class="conversation-actions">
                <button
                  class="delete-btn"
                  @click.stop="deleteConversation(conversation.id)"
                >
                  🗑️
                </button>
              </view>
            </view>
            <view class="conversation-meta">
              <text class="conversation-date">{{
                formatRelativeTime(conversation.createdAt)
              }}</text>
              <text class="conversation-messages-count">
                {{ conversation.messagesCount || 0 }} 条消息
              </text>
            </view>
          </view>
          <view class="conversation-arrow">→</view>
        </view>

        <!-- 加载更多 -->
        <view v-if="loading" class="loading-more">
          <text>加载中...</text>
        </view>

        <!-- 没有更多数据 -->
        <view v-if="noMore && conversations.length > 0" class="no-more">
          <text>没有更多对话了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 新建对话弹窗 -->
    <view
      v-if="showNewChatDialog"
      class="dialog-overlay"
      @click="hideNewChatDialog"
    >
      <view class="dialog-content" @click.stop>
        <view class="dialog-header">
          <text class="dialog-title">新建对话</text>
          <button class="close-btn" @click="hideNewChatDialog">✕</button>
        </view>
        <view class="dialog-body">
          <input
            v-model="newChatTitle"
            class="title-input"
            placeholder="请输入对话标题（可选）"
            maxlength="50"
          />
          <view class="dialog-actions">
            <button class="cancel-btn" @click="hideNewChatDialog">取消</button>
            <button
              class="confirm-btn"
              @click="confirmCreateChat"
              :disabled="creating"
            >
              <text v-if="!creating">创建</text>
              <text v-else>创建中...</text>
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { chatAPI } from "@/api/index";

// 响应式数据
const conversations = ref([]);
const loading = ref(false);
const refreshing = ref(false);
const creating = ref(false);
const showNewChatDialog = ref(false);
const newChatTitle = ref("");
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 计算属性
const noMore = computed(
  () => conversations.value.length >= total.value && total.value > 0
);

// 生命周期
onMounted(() => {
  loadConversations();
});

// 加载对话列表
const loadConversations = async (refresh = false) => {
  if (refresh) {
    page.value = 1;
    conversations.value = [];
  }

  if (loading.value) return;

  try {
    loading.value = true;
    const response = await chatAPI.getConversations(page.value, pageSize.value);

    const items = response.items || response.Items || [];
    const totalCount = response.totalCount || response.TotalCount || 0;

    if (refresh) {
      conversations.value = items;
    } else {
      conversations.value.push(...items);
    }
    total.value = totalCount;
  } catch (error) {
    console.error("加载对话失败:", error);
    uni.showToast({
      title: "加载失败，请重试",
      icon: "none",
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 刷新
const onRefresh = () => {
  refreshing.value = true;
  loadConversations(true);
};

// 加载更多
const loadMore = () => {
  if (!noMore.value && !loading.value) {
    page.value++;
    loadConversations();
  }
};

// 创建新对话
const createNewChat = () => {
  showNewChatDialog.value = true;
  newChatTitle.value = "";
};

// 隐藏新建对话弹窗
const hideNewChatDialog = () => {
  showNewChatDialog.value = false;
  newChatTitle.value = "";
};

// 确认创建对话
const confirmCreateChat = async () => {
  if (creating.value) return;

  try {
    creating.value = true;
    const title =
      newChatTitle.value.trim() || `对话_${new Date().toLocaleString()}`;

    const response = await chatAPI.createConversation(title);

    if (response && response.id) {
      uni.showToast({
        title: "创建成功",
        icon: "success",
      });

      hideNewChatDialog();
      // 跳转到对话页面
      uni.navigateTo({
        url: `/pages/chat/conversation?id=${
          response.id
        }&title=${encodeURIComponent(title)}`,
      });
    }
  } catch (error) {
    console.error("创建对话失败:", error);
    uni.showToast({
      title: "创建失败，请重试",
      icon: "none",
    });
  } finally {
    creating.value = false;
  }
};

// 打开对话
const openConversation = (conversation) => {
  uni.navigateTo({
    url: `/pages/chat/conversation?id=${
      conversation.id
    }&title=${encodeURIComponent(conversation.title || "新对话")}`,
  });
};

// 删除对话
const deleteConversation = async (conversationId) => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这个对话吗？删除后无法恢复。",
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '删除中...',
            mask: true
          });
          
          await chatAPI.deleteConversation(conversationId);
          
          uni.hideLoading();
          uni.showToast({
            title: "删除成功",
            icon: "success",
            duration: 1500
          });

          // 从本地列表中移除已删除的对话，而不是重新加载整个列表
          const index = conversations.value.findIndex(c => c.id === conversationId);
          if (index !== -1) {
            conversations.value.splice(index, 1);
            total.value--;
          }
          
        } catch (error) {
          uni.hideLoading();
          console.error("删除对话失败:", error);
          uni.showToast({
            title: error.message || "删除失败，请重试",
            icon: "none",
            duration: 2000
          });
        }
      }
    },
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 格式化相对时间
const formatRelativeTime = (dateString) => {
  const date = new Date(dateString);
  const now = new Date();
  const diff = now - date;

  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (minutes < 1) return "刚刚";
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;

  return date.toLocaleDateString();
};
</script>

<style scoped>
.chat-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  padding: 10px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.back-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.back-icon {
  font-size: 20px;
  color: #333;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.new-chat-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 14px;
}

.new-chat-icon {
  font-size: 16px;
}

.conversations-list {
  flex: 1;
  padding: 20px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.empty-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 30px;
}

.empty-action-btn {
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 25px;
  padding: 12px 30px;
  font-size: 16px;
}

.conversations-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.conversation-item {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.conversation-content {
  flex: 1;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.conversation-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.conversation-actions {
  display: flex;
  gap: 10px;
}

.delete-btn {
  background: none;
  border: none;
  font-size: 16px;
  padding: 5px;
}

.conversation-meta {
  display: flex;
  gap: 15px;
  align-items: center;
}

.conversation-date {
  font-size: 12px;
  color: #999;
}

.conversation-messages-count {
  font-size: 12px;
  color: #666;
  background-color: #f0f0f0;
  padding: 2px 8px;
  border-radius: 10px;
}

.conversation-arrow {
  font-size: 18px;
  color: #ccc;
  margin-left: 15px;
}

.loading-more,
.no-more {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 12px;
  width: 80%;
  max-width: 400px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0;
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  padding: 5px;
}

.dialog-body {
  padding: 20px;
}

.title-input {
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 12px;
  font-size: 16px;
  margin-bottom: 20px;
}

.dialog-actions {
  display: flex;
  gap: 15px;
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  padding: 12px;
  border-radius: 8px;
  font-size: 16px;
  border: none;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #007aff;
  color: white;
}

.confirm-btn:disabled {
  background-color: #ccc;
}
</style>
